package com.sise.cn.controller;

import com.sise.cn.annotation.AccessAuthority;
import com.sise.cn.api.common.config.LoginConfig;
import com.sise.cn.api.common.impl.helper.LoginHelper;
import com.sise.cn.api.common.po.BaseUserPO;
import com.sise.cn.api.common.service.LoginValidService;
import com.sise.cn.constant.CommonConstant;
import com.sise.cn.constant.RedisConstant;
import com.sise.cn.redis.cache.RedisUtil;
import com.sise.cn.utils.LoginAccountInfo;
import com.sise.cn.vo.HttpBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description
 * @Author CCJ
 * @Date 2020/6/10 15:45
 **/
public abstract class LoginController {
    @Autowired
    protected LoginValidService loginValidService;

    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    protected LoginConfig loginConfig;

    @ResponseBody
    @AccessAuthority
    @GetMapping("/preLogin")
    public HttpBody preLogin(HttpServletRequest request) {
        String type;
        if (request.getRequestURI().contains("/admin/")) {
            type = "admin";
        } else {
            type = "customer";
        }
        String key = RedisConstant.LOGIN_FAIL_COUNT_KEY
                .replace("{ip}", LoginHelper.getRealIP(request))
                .replace("{type}", type);
        long failCount = redisUtil.get(key, Long.class);
        Map<String, Object> map = new HashMap<>();
        if (failCount >= loginConfig.getFailCount()) {
            map.put("needVerifyCode", true);
            return HttpBody.getSucInstance(map);
        }
        map.put("needVerifyCode", false);
        return HttpBody.getSucInstance(map);
    }

    protected void loginin(BaseUserPO param, HttpServletRequest request,
                           HttpServletResponse response, boolean isAdmin) throws IOException {
        LoginAccountInfo accountInfo = loginValidService.handleLogin(param, request);
        Cookie cookie = new Cookie(CommonConstant.COOKIE_TOKEN, accountInfo.getToken());
        response.addCookie(cookie);
        if (isAdmin){
            response.sendRedirect(loginConfig.getAdmin().getIndexUrl());
        }else {
            response.sendRedirect(loginConfig.getCustomer().getIndexUrl());
        }
    }
}
